package com.talos.ums.service.warehouseuser;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.warehouseuser.vo.UmsWarehouseUserPageReqVO;
import com.talos.ums.controller.admin.warehouseuser.vo.UmsWarehouseUserSaveReqVO;
import com.talos.ums.dal.dataobject.warehouseuser.UmsWarehouseUserDO;
import com.talos.ums.dal.mysql.warehouseuser.UmsWarehouseUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户仓库关系表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsWarehouseUserServiceImpl implements UmsWarehouseUserService {

    @Resource
    private UmsWarehouseUserMapper warehouseUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createWarehouseUser(UmsWarehouseUserSaveReqVO createReqVO) {
        // 插入
        UmsWarehouseUserDO warehouseUser = BeanUtils.toBean(createReqVO, UmsWarehouseUserDO.class);
        warehouseUserMapper.insert(warehouseUser);
        // 返回
        return warehouseUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWarehouseUser(UmsWarehouseUserSaveReqVO updateReqVO) {
        // 校验存在
        validateWarehouseUserExists(updateReqVO.getId());
        // 更新
        UmsWarehouseUserDO updateObj = BeanUtils.toBean(updateReqVO, UmsWarehouseUserDO.class);
        warehouseUserMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWarehouseUser(Long id) {
        // 校验存在
        validateWarehouseUserExists(id);
        // 删除
        warehouseUserMapper.deleteById(id);
    }

    private void validateWarehouseUserExists(Long id) {
        if (warehouseUserMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsWarehouseUserDO getWarehouseUser(Long id) {
        return warehouseUserMapper.selectById(id);
    }

    @Override
    public PageResult<UmsWarehouseUserDO> getWarehouseUserPage(UmsWarehouseUserPageReqVO pageReqVO) {
        return warehouseUserMapper.selectPage(pageReqVO);
    }

}
